<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{Taocans, TaocansLog, PaymentList, User as Users, Address, Promo, MoneyLog, Region, Cart, Product, Coupon, OrderProduct, Order, Pkey, Agent, Payment, Wechat, UserLevel, Riderlist, RiderStreet, IntergralLog, Message};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;

class User extends Base
{

    public function gettaocan()
    {
        if ($this->request->isPost()) {
            $this->result([], 1, '暂不支持添加购物车');
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require'
            ], [
                'id.require' => '套餐ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $agentid = $this->request->user['agentid'];
            $taocan = (new Taocans())->where(['isshow' => 1, 'agentid' => $agentid, 'id' => $data['id']])->find();
            if (empty($taocan)) {
                $this->result([], 1, '组合不存在,添加失败');
            }
            $taocanlog = (new TaocansLog())->where(['taocansid' => $taocan['id']])->select();
            if (empty($taocanlog)) {
                $this->result([], 1, '组合产品不存在,添加失败');
            }
            $save = [];
            $saves = [];
            foreach ($taocanlog as $log) {
                $product = (new Product())->where(['isdel' => 1, 'isremove' => 1, 'agentid' => $agentid, 'id' => $log['productid']])->find();
                if (!empty($product)) {
                    $cart = (new Cart())->where(['user_id' => $this->request->user_id, 'productid' => $product['id']])->find();
                    if (empty($cart)) {
                        $save[] = [
                            'user_id' => $this->request->user_id,
                            'agentid' => $product['agentid'],
                            'cate' => $product['cate'],
                            'subcate' => $product['subcate'],
                            'productid' => $product['id'],
                            'number' => $log['numbers']
                        ];
                    } else {
                        $saves[] = [
                            'id' => $cart['id'],
                            'user_id' => $this->request->user_id,
                            'agentid' => $product['agentid'],
                            'cate' => $product['cate'],
                            'subcate' => $product['subcate'],
                            'productid' => $product['id'],
                            'number' => $log['numbers']
                        ];
                    }
                }
            }
            Db::startTrans();
            try {
                if (count($save) > 0) {
                    (new Cart())->allowfield(true)->saveAll($save);
                }
                if (count($saves) > 0) {
                    (new Cart())->allowfield(true)->saveAll($saves);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败');
            }
            $this->result([], 0, '操作成功');
        } else {
            if (empty($this->request->user_id)) {
                $this->result([], 0, '获取成功');
            }
            $agentid = $this->request->user['agentid'];
            $tabtype = $this->request->get('tabtype/d', 0);
            $taocan = (new Taocans())->where(['isdel' => 1, 'isshow' => 1, 'agentid' => $agentid])
                ->where('numbers', '>', 0)
                ->order(['sorts' => 'desc', 'id' => 'desc']);
            if (!empty($tabtype)) {
                $taocan = $taocan->where('tabtype', $tabtype);
            }
            $taocan = $taocan->select();
            foreach ($taocan as $list) {
                $goods = (new TaocansLog())->alias('t')
                    ->join('product p', 'p.id = t.productid')
                    ->where(['p.isdel' => 1, 'p.isremove' => 1, 'p.agentid' => $agentid, 't.taocansid' => $list['id']])
                    ->field('t.numbers as number,t.productid,p.images,p.title,p.price,p.inventory,p.parame')
                    ->select();
                $total = 0;
                $count = 0;
                foreach ($goods  as $good) {
                    $good['parame'] = json_decode($good['parame'], true) ?? [];
                    $total += $good['price'] * $good['number'];
                    $count += $good['number'];
                    $good['price'] = (float)$good['price'];
                }
                $list['goods'] = $goods;
                $list['count'] = $count;
                $list['total'] = $total;
                $list['sendmoney'] = (float)(new Agent())->where(['id' => $agentid, 'status' => 1])->value('sendmoney') ?? 0;
            }
            $this->result($taocan, 0, '获取成功');
        }
    }

    public function edituser()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'password' => 'require'
        ], [
            'password.require' => '修改密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Users())->where('id', $this->request->user_id)->find();
        if ($user['password'] == md5(md5($data['password']))) {
            $this->result([], 1, '密码与原密码一致');
        }
        $res = (new Users())->where('id', $this->request->user_id)->update(['password' => md5(md5($data['password'])), 'yspassword' => $data['password']]);
        if ($res) {
            $this->result([], 0, '修改成功');
        }
        $this->result([], 1, '修改失败，请重试');
    }

    public function getlogin()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require'
        ], [
            'mobile.require' => '账号不能为空',
            'password.require' => '密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Users())->field('status,yspassword,created,issystem,agentid', true)->where('mobile', $data['mobile'])->find();
        if (empty($user)) {
            $this->result([], 1, '账号不存在，请联系相关人员开通');
        }
        if ($user['password'] != md5(md5($data['password']))) {
            $this->result([], 1, '账号密码错误');
        }
        $token = 'user_' . md5(time() . $user['id']);
        Redis::setex($token, 15 * 86400, $user['id']);
        $this->result(['token' => $token, 'user' => $user], 0, '登录成功');
    }


    public function address()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'mobile' => 'require',
                'street' => 'require',
                'address' => 'require',
                'is_default' => 'require|in:1,2',
                // 'getaddress' => 'require',
                // 'lat' => 'require',
                // 'lon' => 'require',
            ], [
                'name.require' => '联系人姓名不能为空',
                'mobile.require' => '联系人电话不能为空',
                'street.require' => '街道ID不能为空',
                'address.require' => '具体地址不能为空',
                // 'getaddress.require' => '定位地址不能为空',
                'is_default.require' => '默认类型不能为空',
                'is_default.in' => '默认类型不正确',
                // 'lat.require' => '经度不能为空',
                // 'lon.require' => '纬度不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $streets = getdrees($data['street']);
            if (empty($streets['street']) || empty($streets['area']) || empty($streets['city']) || empty($streets['province'])) {
                $this->result([], 1, '添加错误，请重试或退出页面重新编辑');
            }
            $data['street'] = $streets['street'];
            $data['area'] = $streets['area'];
            $data['city'] = $streets['city'];
            $data['province'] = $streets['province'];
            $data['user_id'] = $this->request->user_id;
            $addressmodel = new Address();
            Db::startTrans();
            try {
                (new Address())->where('user_id', $this->request->user_id)->update(['is_default' => 1]);
                if (!empty($data['id'])) {
                    $addressmodel->allowfield(true)->save($data, ['id' => $data['id']]);
                } else {
                    $addressmodel->allowfield(true)->save($data);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败');
            }
            $this->result([], 0, '操作成功');
        } else {
            $addressmodel = new Address();
            $result = $addressmodel->where('user_id', $this->request->user_id)->order('is_default desc')->field('user_id,created', true)->select();
            foreach ($result as $results) {
                $address_name = getdrees($results['street'], 1);
                $results['province_name'] = $address_name['province'];
                $results['city_name'] = $address_name['city'];
                $results['area_name'] = $address_name['area'];
                $results['street_name'] = $address_name['street'];
            }
            $this->result($result, 0, '操作成功');
        }
    }


    public function address_del()
    {
        $id = $this->request->post('id/d', 0);
        $addressmodel = new Address();
        $result = $addressmodel->where(['user_id' => $this->request->user_id, 'id' => $id])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function cart_del()
    {
        $id = $this->request->post('ids/s');
        $ids  = json_decode($id, true) ?? [];
        if (empty($ids)) {
            $this->result([], 1, '数据为空，操作失败');
        }
        $model = new Cart();
        $result = $model->where(['user_id' => $this->request->user_id, 'id' => $ids])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function cart()
    {
        if ($this->request->isPost()) {
            if (empty($this->request->user_id)) {
                $this->result(null, 999, '请授权登陆账号');
            }
            $data = $this->request->post();
            $validate = new Validate([
                'productid' => 'require',
                'number' => 'require',
                'type' => 'require|in:1,2'
            ], [
                'productid.require' => '产品ID不能为空',
                'number.require' => '产品数目不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $product = (new Product())->alias('p')
                ->join('agent a', 'p.agentid = a.id')
                ->where(['p.id' => $data['productid'], 'p.isdel' => 1, 'p.isremove' => 1, 'a.status' => 1])
                ->field('p.*')
                ->find();
            if (empty($product)) {
                $this->result([], 1, '产品已下架');
            }
            //查询是否已经添加购物车
            $mycart = (new Cart())->where(['productid' => $data['productid'], 'user_id' => $this->request->user_id])->find();
            $number = (int)$data['number'] ?? 0;
            if ($data['type'] == 1 && !empty($mycart)) {
                $number += $mycart['number'];
            }
            if ($data['type'] == 2 && !empty($mycart) && $number == $mycart['number']) {
                $this->result(['number' => $number], 0, '操作成功');
            }
            $save = [
                'user_id' => $this->request->user_id,
                'cate' =>  $product['cate'],
                'agentid' => $product['agentid'],
                'productid' => $data['productid'],
                'number' => $number
            ];
            // if($save['number'] > $product['inventory']){
            //     $this->result([], 1, '产品库存不足');
            // }
            if (!empty($mycart)) {
                if ($number <= 0) {
                    $res =  (new Cart())->where('id', $mycart['id'])->delete();
                } else {
                    $res =  (new Cart())->allowfield(true)->save($save, ['id' => $mycart['id']]);
                }
            } else {
                if ($number <= 0) {
                    $res = true;
                } else {
                    $res =  (new Cart())->allowfield(true)->save($save);
                }
            }
            if ($res) {
                $this->result(['number' => $number], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $agentid = $this->request->user['agentid'];
            $goods = (new Cart())->alias('c')
                ->join('product p', 'p.id = c.productid')
                ->where(['p.isdel' => 1, 'p.isremove' => 1, 'c.agentid' => $agentid, 'c.user_id' => $this->request->user_id])
                ->field('c.id,c.number,c.productid,p.images,p.title,p.price,p.inventory,p.parame')
                ->select();
            $total = 0;
            $count = 0;
            foreach ($goods  as $good) {
                $good['parame'] = json_decode($good['parame'], true) ?? [];
                $total += $good['price'] * $good['number'];
                $count += $good['number'];
            }
            $list['goods'] = $goods;
            $list['count'] = $count;
            $list['total'] = $total;
            $list['sendmoney'] = (float)(new Agent())->where(['id' => $agentid, 'status' => 1])->value('sendmoney') ?? 0;
            $this->result($list, 0, '获取成功');
        }
    }

    public function putorder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'productid' => 'require',
            'addressid' => 'require'
        ], [
            'productid.require' => '规格ID不能为空',
            'addressid.require' => '联系信息不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        Log::write($data, 'test');
        if (!is_array($data['productid'])) {
            $data['productid'] = json_decode($data['productid'], true) ?? [];
        }
        if (empty($data['productid']) || !is_array($data['productid'])) {
            $this->result([], 1, '产品数据错误');
        }
        if (!empty($data['cartid'])) {
            $data['cartid'] = json_decode($data['cartid'] ?? '', true) ?? [];
        }
        //查询地址是否存在
        $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
        if (empty($address)) {
            $this->result([], 1, '地址信息不存在');
        }
        $order = [
            'user_id' => $this->request->user_id,
            'taocanid' => $data['taocanid'] ?? 0,
            'ordersn' => reordersn(new Order()),
            'agentid' =>  $this->request->user['agentid'] ?? 0,
            'name' => $address['name'],
            'mobile' => $address['mobile'],
            'province' => $address['province'],
            'city' => $address['city'],
            'area' => $address['area'],
            'street' => $address['street'],
            'posaddress' => $address['getaddress'],
            'address' => $address['address'],
            'lat' => $address['lat'],
            'lon' => $address['lon'],
            'info' => $data['info'] ?? '',
            'status' => 1,
            'ptotal' => 0,
            'total' => 0,
        ];
        $orderproduct = [];
        $agentinfo = (new Agent())->where(['id' => $order['agentid'], 'status' => 1])->find();
        if (empty($agentinfo)) {
            $this->result([], 1, '品牌通道已关闭');
        }
        foreach ($data['productid'] as $product) {
            if (empty($product['id'])  || empty($product['number'])) {
                $this->result([], 1, '产品参数错误');
            }
            //查询规格是否存在
            $products = (new Product())->where(['isdel' => 1, 'isremove' => 1, 'id' => $product['id'], 'agentid' => $order['agentid']])->find();
            if (empty($products)) {
                $this->result([], 1, '产品已下架,请刷新页面重新提交订单');
            }
            if ($product['number'] > $products['inventory']) {
                $this->result([], 1, $products['title'] . '剩余库存为' . $products['inventory'] . ',请调整库存后下单');
            }
            //查找下面有没有相关服务人员
            $orderproduct[] = [
                'ordersn' => $order['ordersn'],
                'agentid' => $order['agentid'],
                'taocanid' => $data['taocanid'] ?? 0,
                'cate' => $products['cate'],
                'subcate' => $products['subcate'],
                'productid' => $products['id'],
                'title' =>  $products['title'],
                'descs' =>  $products['descs'],
                'images' =>  $products['images'],
                'price' =>  $products['price'],
                'number' =>  $product['number'],
                'numbers' =>  $product['number'],
                'type' => $products['type'],
                'parame' => $products['parame'] ?? '',
                'cnumber' => 0,
                'cid' => ''
            ];
            $order['ptotal'] += $product['number'] * $products['price'];
        }
        if ($order['ptotal'] < $agentinfo['sendmoney']) {
            $this->result([], 1, '低于起送价');
        }
        $order['total'] = $order['ptotal'];
        $text = '下单成功，请支付后等待确认审核';
        if ($order['total'] <= 0) {
            $order['total'] = 0;
            $order['status'] = 2;
            $text = '下单成功';
        }
        Db::startTrans();
        try {
            (new Order())->save($order);
            (new OrderProduct())->allowfield(true)->saveAll($orderproduct);
            if (!empty($data['cartid'])) {
                (new Cart())->where(['id' => $data['cartid'], 'user_id' => $this->request->user_id])->delete();
            }
            foreach ($orderproduct as $oproduct) {
                (new Product())->SkuEdit($oproduct['productid'], -$oproduct['number'], $oproduct['number'], 1, '下单成功');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, $e->getMessage());
        }
        $this->result(['ordersn' => $order['ordersn'], 'status' => $order['status']], 0, $text);
    }

    public function info()
    {
        $user = $this->request->user;
        $result = [
            'id' => $user['id'],
            'name' => $user['name'] ?? '未设置',
            'nickName' => $user['nickName'] ?? '未设置',
            'avatarUrl' => $user['avatarUrl'] ?? '',
            'mobile' => $user['mobile'] ?? '未获取',
            'infodetail' => (new Agent())->where('id', $user['agentid'])->value('detail') ?? ''
        ];
        $this->result($result, 0, '获取成功');
    }

    public function orderstatus()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'ordersn' => 'require',
            'status' => 'require|in:2,4,5'
        ], [
            'ordersn.require' => '订单编号不能为空',
            'status.require' => '状态不能为空',
            'status.in' => '状态不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where('ordersn', $data['ordersn'])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        switch ($data['status']) {
            case '2':
                if ($order['status'] != 1 && $order['status'] != 2) {
                    $this->result([], 1, '订单不处于支付确认状态');
                }
                if (empty($data['payment'])) {
                    $this->result([], 1, '订单支付方式错误');
                }
                if ($data['payment'] == 1) {
                    if (empty($data['images'])) {
                        $this->result([], 1, '请上传付款凭证');
                    }
                    $imagesArr = [];
                    foreach ($data['images'] as $imagesd) {
                        if (!empty($imagesd['url'])) {
                            $imagesArr[] = $imagesd;
                        }
                    }
                    if (count($imagesArr) <= 0) {
                        $this->result([], 1, '付款凭证信息错误,请重试');
                    }
                    $paytimes = empty($order['paytimes']) ? date('Y-m-d H:i:s') : $order['paytimes'];
                    //支付订单
                    Db::startTrans();
                    try {
                        (new Order())->where('id', $order['id'])->update(['status' => $data['status'], 'paytime' => $paytimes, 'payment' => $data['payment'], 'images' => json_encode($imagesArr, true), 'examine' => 1]);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $this->result([], 0, '操作成功');
                } else {
                    $this->result([], 1, '支付类型错误');
                }
                break;
            case '4':
                if ($order['status'] != 3) {
                    $this->result([], 1, '订单状态不可完成');
                }
                //完成订单
                Db::startTrans();
                try {
                    (new Order())->where('id', $order['id'])->update(['status' => $data['status'], 'endtime' => date('Y-m-d H:i:s')]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->result([], 1, $e->getMessage());
                }
                $this->result([], 0, '操作成功');
                break;
            case '5':
                if ($order['status'] == 4) {
                    $this->result([], 1, '订单已完成不可取消');
                }
                if ($order['status'] == 5) {
                    $this->result([], 1, '订单已取消');
                }
                $msg = '取消成功';
                if ($order['status'] != 1 && $order['examine'] != 2) {
                    $this->result([], 1, '订单状态不可取消，如需取消请联系平台');
                }
                //取消
                $data['refund'] = $order['refund'];
                if ($order['status'] >= 2 && $order['total'] > 0 && $order['payment'] > 1) {
                    $data['refund'] = 2;
                    $msg = "取消成功";
                }
                $orderproduct = (new OrderProduct())->where('ordersn', $order['ordersn'])->select();
                Db::startTrans();
                try {
                    (new Order())->where('id', $order['id'])->update([
                        'status' => $data['status'],
                        'caceltime' => date('Y-m-d H:i:s'),
                        'refund' => $data['refund']
                    ]);
                    foreach ($orderproduct as $oproduct) {
                        (new Product())->SkuEdit($oproduct['productid'], $oproduct['number'], -$oproduct['number'], 2, '取消订单');
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->result([], 1, $e->getMessage());
                }
                $this->result([], 0, $msg);
                break;
            default:
                $this->result([], 1, '状态出错');
                break;
        }
    }

    public function orderlist()
    {
        if (empty($this->request->user_id)) {
            $this->result([], 0, '获取成功');
        }
        $status = $this->request->get('status/d', '');
        $list = (new Order())->order('id desc');
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        $list = $list->where('user_id', $this->request->user_id)->field('id,agentid,ordersn,status,total,refund,created,examine')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['tnumber'] = 0;
            $ordergoods = (new OrderProduct())->field('productid,title,descs,images,price,number,cnumber')->where(['ordersn' => $lists['ordersn']])->select();
            foreach ($ordergoods as $goods) {
                $lists['tnumber'] += $goods['number'];
            }
            $lists['goods'] = $ordergoods;
            $lists['status_text'] = $lists->status_text;
        }
        $this->result($list, 0, '获取成功');
    }


    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Order())->where('id', $id)->field('id,examine,images,agentid,payment,ordersn,ptotal,total,created,info,status,street,name,mobile,posaddress,address,refund')->find();
        if ($list) {
            $list['status_text'] = $list->status_text;
            $list['payment_text'] = $list->payment_text;
            $goods = (new OrderProduct())->where('ordersn', $list['ordersn'])->field('images,number,title,price,cnumber')->select();
            $list['good'] = $goods;
            $payment = (new PaymentList())->where(['agentid' => $list['agentid'], 'isdel' => 1])->select();
            $list['payment'] = $payment;
            $list['images'] = json_decode($list['images'], true);
        }
        $this->result($list, 0, '获取成功');
    }

    public function  message()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'message' => 'require',
                'type' => 'require|in:1,2,3',
            ], [
                'message.require' => '反馈内容为空',
                'type.require' => '反馈类型不能为空',
                'type.in' => '反馈类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['messtype'] = $data['type'];
            $data['type'] = 1;
            $data['user_id'] = $this->request->user_id;
            if (!empty($data['images'])) {
                $images = json_decode($data['images'] ?? '', true) ?? [];
                if (is_array($images) && count($images) > 0) {
                    $data['images'] = json_encode($images, true);
                } else {
                    $data['images'] = '';
                }
            } else {
                $data['images'] = '';
            }
            $res = (new Message())->allowfield(true)->save($data);
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败');
        } else {
            $list = (new Message())->order('id desc');
            $list = $list->where(['user_id' =>  $this->request->user_id, 'type' => 1])
                ->field('message,reply,mobile,created,images,messtype')
                ->paginate(20, false, ['query' => $this->request->param()])->each(function ($item) use ($list) {
                    $item['images'] = json_decode($item['images'], true) ?? [];
                    $item['type_text'] = $item->type_text;
                    return $item;
                });
            $this->result($list, 0, '查询完成');
        }
    }
}
